package com.ruoyi.web.controller.system;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.Allergy;
import com.ruoyi.system.domain.HealthRegister;
import com.ruoyi.system.service.IHealthRegisterService;
import com.ruoyi.web.controller.enums.ExamineFlagEnum;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.Family;
import com.ruoyi.system.service.IFamilyService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 家族成员Controller
 * 
 * @author ruoyi
 * @date 2021-05-10
 */
@Controller
@RequestMapping("/system/family")
public class FamilyController extends BaseController
{
    private String prefix = "system/family";

    @Autowired
    private IFamilyService familyService;

    @Autowired
    private IHealthRegisterService healthRegisterService;

    @RequiresPermissions("system:family:view")
    @GetMapping()
    public String family()
    {
        return prefix + "/family";
    }

    /**
     * 查询家族成员列表
     */
    @RequiresPermissions("system:family:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(Family family)
    {
        startPage();
        family.setUserId(ShiroUtils.getUserId());
        List<Family> list = familyService.selectFamilyList(family);
        return getDataTable(list);
    }

    /**
     * 导出家族成员列表
     */
    @RequiresPermissions("system:family:export")
    @Log(title = "家族成员", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(Family family)
    {
        List<Family> list = familyService.selectFamilyList(family);
        ExcelUtil<Family> util = new ExcelUtil<Family>(Family.class);
        return util.exportExcel(list, "家族成员数据");
    }

    /**
     * 新增家族成员
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存家族成员
     */
    @RequiresPermissions("system:family:add")
    @Log(title = "家族成员", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    @Transactional
    public AjaxResult addSave(Family family)
    {
        family.setUserId(ShiroUtils.getUserId());
        int result = familyService.insertFamily(family);
        HealthRegister healthRegister = new HealthRegister();
        healthRegister.setUserId(ShiroUtils.getUserId());
        healthRegister.setFamilyId(family.getId());
        healthRegister.setName(family.getName());
        healthRegister.setSex(family.getSex());
        healthRegisterService.insertHealthRegister(healthRegister);
        return toAjax(result);
    }

    /**
     * 修改家族成员
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        Family family = familyService.selectFamilyById(id);
        mmap.put("family", family);
        return prefix + "/edit";
    }

    /**
     * 修改保存家族成员
     */
    @RequiresPermissions("system:family:edit")
    @Log(title = "家族成员", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    @Transactional
    public AjaxResult editSave(Family family)
    {
        family.setUserId(ShiroUtils.getUserId());
        HealthRegister healthRegister = healthRegisterService.selectHealthRegisterById(family.getId());
        healthRegister.setName(family.getName());
        healthRegister.setSex(family.getSex());
        healthRegisterService.updateHealthRegister(healthRegister);
        return toAjax(familyService.updateFamily(family));
    }

    /**
     * 查看健康档案
     */
    @GetMapping("/query_health/{id}")
    public String queryHealth(@PathVariable("id") Long id, ModelMap mmap)
    {
        HealthRegister healthRegister = healthRegisterService.selectHealthRegisterByFamilyId(id);
        mmap.put("healthRegister", healthRegister == null ? new HealthRegister(): healthRegister);
        return prefix + "/health_query";
    }

    /**
     * 修改健康档案
     */
    @GetMapping("/health/{id}")
    public String health(@PathVariable("id") Long id, ModelMap mmap)
    {
        HealthRegister healthRegister = healthRegisterService.selectHealthRegisterByFamilyId(id);
        mmap.put("healthRegister", healthRegister == null ? new HealthRegister(): healthRegister);
        return prefix + "/health_edit";
    }

    /**
     * 修改健康档案保存
     */
    @RequiresPermissions("system:family:edit")
    @Log(title = "健康档案", businessType = BusinessType.UPDATE)
    @PostMapping("/healthSave")
    @ResponseBody
    public AjaxResult healthSave(HealthRegister healthRegister)
    {
        healthRegister.setUserId(ShiroUtils.getUserId());
        //民族
        if(StringUtils.isNotBlank(healthRegister.getNationText())){
            Map<Integer, String> nationMap = new HashMap<>();
            nationMap.put(healthRegister.getNationKey(), healthRegister.getNationText());
            healthRegister.setNationJson(JSONObject.toJSONString(nationMap));
        }
        Map<String, String> extraMap = new HashMap();
        //疾病史
        String disease = JSONObject.toJSONString(healthRegister.getDiseaseList());
        extraMap.put("disease", disease);
        //手术史
        if(healthRegister.getOperation().getCode() != null){
            extraMap.put("operation",JSONObject.toJSONString(healthRegister.getOperation()));
        }
        //外伤史
        if(healthRegister.getTrauma().getCode() != null){
            extraMap.put("trauma",JSONObject.toJSONString(healthRegister.getTrauma()));
        }
        //输血史
        if(healthRegister.getMetachysis().getCode() != null){
            extraMap.put("metachysis",JSONObject.toJSONString(healthRegister.getMetachysis()));
        }
        //过敏史
        String allergy = JSONObject.toJSONString(healthRegister.getAllergyList());
        extraMap.put("allergy",allergy);
        //过敏史其他
        extraMap.put("allergyOther", healthRegister.getAllergyOther());

        //遗传病史
        if(healthRegister.getHeritable().getCode() != null){
            extraMap.put("heritable", JSONObject.toJSONString(healthRegister.getHeritable()));
        }

        //残疾情况
        String disability = JSONObject.toJSONString(healthRegister.getDisabilityList());
        extraMap.put("disability",disability);
        //其他残疾
        extraMap.put("disabilityOther", healthRegister.getDisabilityOther());

        if(!extraMap.isEmpty()){
            String extraJSON = JSONObject.toJSONString(extraMap);
            healthRegister.setExtraJson(extraJSON);
        }
        return toAjax(healthRegisterService.updateHealthRegister(healthRegister));

    }

    /**
     * 删除家族成员
     */
    @RequiresPermissions("system:family:remove")
    @Log(title = "家族成员", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    @Transactional
    public AjaxResult remove(String ids)
    {
        healthRegisterService.deleteHealthRegisterByIds(ids);
        return toAjax(familyService.deleteFamilyByIds(ids));
    }


    @ResponseBody
    @PostMapping("/submitExamine")
    @RequiresPermissions("system:family:edit")
    @Log(title = "提交审核", businessType = BusinessType.UPDATE)
    public AjaxResult submitExamine(Long familyId){
        HealthRegister healthRegister = healthRegisterService.selectHealthRegisterByFamilyId(familyId);
        healthRegister.setFlag(ExamineFlagEnum.SUBMIT.getCode());
        healthRegister.setSubmitTime(new Date());
        return toAjax(healthRegisterService.updateHealthRegister(healthRegister));
    }


}
